package com.better.common.jwtauth.user;

import com.better.common.jwtauth.secruity.JWTUserDetails;
import com.better.common.utils.SessionUtils;
import com.better.common.base.ServiceResponse;
import com.better.common.utils.ServiceResponseHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 *restful api 例子
*@author:wfm
*@date :2018/2/27
*/
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository repository;
    //获取所有用户信息
    //url：http://localhost:8089/users
    @RequestMapping(method = RequestMethod.GET)
    public List<User> getUsers() {
        return repository.findAll();
    }
    //新增用户信息
    //url：http://localhost:8089/users
    @RequestMapping(method = RequestMethod.POST)
    User addUser(@RequestBody User addedUser) {
        return repository.insert(addedUser);
    }

   //根据用户ID获取用户信息
    //url:http://localhost:8089/users/123456
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable String id) {
        return repository.findOne(id);
    }
   //修改用户信息
    //url：http://localhost:8089/users/123456
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    User updateUser(@PathVariable String id, @RequestBody User updatedUser) {
        updatedUser.setId(id);
        return repository.save(updatedUser);
    }
    //根据ID删除用户信息
    //url:http://localhost:8089/users/123456
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    User removeUser(@PathVariable String id) {
        User deletedUser = repository.findOne(id);
        repository.delete(id);
        return deletedUser;
    }












    @RequestMapping(value = "getUser",method = RequestMethod.GET)
    @Cacheable(value = "users",keyGenerator="keyGenerator")
    public ServiceResponse getUserByUsername(@RequestParam(value="username") String username) {
        JWTUserDetails jwtUserDetails =SessionUtils.getUserInfo();
        System.out.println(jwtUserDetails.toString());
        return ServiceResponseHandle.success(repository.findByUsername(username));
    }
}
